(function (window, $, undefined) {
  'use strict';

  var dictData = {
    status: {
      '0': '已使用',
      '1': '未使用'
    },
    cityId: {},
    plan: {},
    coupon_type: {},
    mutualType: {
      '1': '不互斥',
      '2': '全部互斥',
      '3': '指定互斥'
    }
  };

  var allPlan = [];

  var planData = {};
  var now = util.getTime(util.getDate(true) + ' 00:00:00');

  main(function () {

    var $tablePlan = $('#table-plan');
    util.jqGrid($tablePlan, {
      url: ajaxURL.COUPON + '/coupon/v1/plan/queryWithPage',
      // datatype: 'json',
      mtype: 'POST',
      autowidth: true,
      height: $(window).height() - 320,
      multiselect: true,
      multiboxonly: true,
      // shrinkToFit: false,
      colModel: [
        { name: 'kid', key: true, hidden: true },
        { label: '序号', name: 'kid', width: 50 },
        { label: '方案名称', name: 'planName', width: 120 },
        { label: '方案编号', name: 'planCode', width: 80 },
        { label: '合作渠道', name: 'cooperationChannel', width: 100 },
        { label: '邀请码', name: 'invitCode', width: 80 },
        {
          label: '互斥方案', name: 'mutualType', width: 100, formatter: function (v, o, r) {
            return dictData.mutualType[v] || '';
          }
        },
        { label: '领取上限', name: 'receiveLimt', width: 100, formatter: function (v, o, r) {
          return v + ' 次';
        }
        },
        // {
        //   label: '已领金额', name: '', width: 100, formatter: function (v, o, r) {
        //     return '100 元';
        //   }
        // },
        {
          label: '有效期', name: 'valid_date', width: 150, formatter: function (v, o, r) {
            var ret = util.getDate(r.validityStartTime) + ' 至 ' + util.getDate(r.validityEndTime);
            if (now > r.validityEndTime) {
              ret += ' (<span class="text-danger">已过期</span>)';
            }
            return ret;
          }
        },
        { label: '备注', name: 'remark', width: 100 }
      ],
      loadComplete: function (res) {
        planData = {};
        if (res && res.data) {
          $.each(res.data, function (_, item) {
            planData[item.kid] = item;
            dictData.plan[item.kid] = item.planName;
          });
        }
      },
      pager: '#pager-plan'
    }, true);

    util.selectHtml($('select[name="status"]'), dictData.status, '', '', '请选择');
    util.selectHtml($('select[name="mutualType"]'), dictData.mutualType, '', '', '请选择');

    // 搜索
    function searchTable() {
      var data = util.formData('#form-search');
      var searchData = {
        cooperationChannel: data.cooperationChannel,
        planCode: data.planCode
      };
      if (data.mutualType) {
        searchData.mutualType = +data.mutualType;
      }
      if (data.validityTime) {
        var temp = data.validityTime.split('至');
        searchData.validityStartTime = util.getTime($.trim(temp[0]) + ' 00:00:00');
        searchData.validityEndTime = util.getTime($.trim(temp[1]) + ' 23:59:59');
      }
      util.searchGrid($tablePlan, searchData);
    }

    $('#btn-search').click(searchTable).click();

    // 有效期
    laydate.render({
      range: '至',
      elem: '#activeData'
    });

    // 有效期
    laydate.render({
      range: '至',
      elem: '#validDate',
      type: 'date',
      done: function (value, date, endDate) {
        var temp = value.split('至');
        $('#validDate').next().val($.trim(temp[0])).next().val($.trim(temp[1]));
      }
    });

    var $formPlan = $('#form-plan');
    var $layerPlan = $('#layer-plan');
    var $input3 = $('#sel-mutual-type').find('input').eq(2);

    var $planList = $('#plan-list');
    var $couponList = $('#coupon-list');

    // 新建
    $('#btn-add').click(function () {
      $planList.empty();
      $couponList.empty();

      util.resetForm($formPlan);

      getAllCoupon(function (coupons) {
        renderCoupon(coupons);

        getAllPlan('', function (plans) {
          if (plans && plans.length > 0) {
            renderPlan(plans);
            $input3.removeAttr('disabled');
          } else {
            $input3.attr('disabled', true);
          }

          util.layerOpen({
            title: false,
            content: $layerPlan,
            area: ['1000px', ''],
            btn: ['新增', '取消'],
            yes: function (index) {
              savePlan();
            }
          });
        });

      });

    });

    function renderCoupon(data) {
      var strCoupon = '<ul>';

      $.each(data, function (_, item) {
        strCoupon += renderLi(item.kid, item.couponName);
      });

      strCoupon += '</ul>';

      $couponList.html(strCoupon);

    }

    function renderLi(kid, couponName) {
      var ret = '<li class="form-inline" data-kid="' + kid + '">';
      ret += '<label title="' + couponName + '"><input class="item-id" type="checkbox" value="' + kid + '"><span class="text">' + couponName + '</span></label>';
      ret += '<input type="number" required min="1" disabled class="item-quantity form-control form-width70">';
      ret += '<span class="text">张</span>';
      return ret;
    }

    function renderPlan(data) {
      var ret = '';
      $.each(data, function (_, item) {
        ret += '<label>';
        ret += '<input type="checkbox" value="' + item.kid + '"><span class="text">' + item.planName + '</span>';
        ret += '</label>';
      });

      $planList.html(ret).addClass('hide');
    }

    $('#sel-mutual-type').on('click', 'input', function () {
      var $this = $(this);
      var val = $this.val();
      if (+val === 3) {
        $planList.removeClass('hide');
      } else {
        $planList.addClass('hide');
      }
    });

    $formPlan.on('click', '.item-id', function () {
      var $this = $(this);
      var checked = $this.prop('checked');
      var $input = $this.parent().next();
      if (checked) {
        $input.removeAttr('disabled');
        if (!$input.val()) {
          $input.addClass('error');
        }
      } else {
        $input.attr('disabled', 'disabled').removeClass('error');
      }
    });

    function getAllCoupon(callback) {
      util.get(ajaxURL.COUPON + '/coupon/getCouponTypeList', function (res) {
        if (res.data && res.data.length > 0) {
          if ($.isFunction(callback)) {
            callback(res.data);
          }
        } else {
          util.tip.warn('暂无可用代金券类型，请添加后再进行操作');
        }
      });
    }

    function getAllPlan(exclude, callback) {
      allPlan.length = 0;
      util.get(ajaxURL.COUPON + '/coupon/v1/plan/getAll', function (res) {
        $.each(res.data, function (_, item) {
          if (exclude && item.kid === +exclude) {
            return;
          }
          allPlan.push(item);
        });

        if ($.isFunction(callback)) {
          callback(allPlan);
        }
      });
    }

    // 查看营销方案
    $('#btn-detail').click(util.oneCheck($tablePlan, function (id) {
      util.resetForm($formPlan);
      $planList.empty();
      $couponList.empty();

      var data = planData[id];
      data.validDate = util.getDate(data.validityStartTime) + ' 至 ' + util.getDate(data.validityEndTime);

      var appointMutexList = (function () {
        var ret = [];
        $.each(data.appointMutexList || [], function (_, item) {
          ret.push(item.mutexId);
        });
        return ret;
      })();

      var couponDetailList = (function () {
        var ret = {};
        $.each(data.couponDetailList || [], function (_, item) {
          ret[item.couponId] = item;
        });
        return ret;
      })();

      getAllCoupon(function (coupons) {
        renderCoupon(coupons);

        getAllPlan(id, function (plans) {
          if (plans && plans.length > 0) {
            renderPlan(plans);
            $input3.removeAttr('disabled');
          } else {
            $input3.attr('disabled', true);
          }

          util.fillForm($formPlan, data);

          $planList.find('input[type="checkbox"]').each(function () {
            var $this = $(this);
            var val = +$this.val();
            if (appointMutexList.indexOf(val) > -1) {
              $this.prop('checked', true);
            }
          });

          $couponList.find('input[type="checkbox"]').each(function () {
            var $this = $(this);
            var val = +$this.val();
            if (couponDetailList[val]) {
              $this.prop('checked', true);
              $this.parent().next().val(couponDetailList[val].couponQty).removeAttr('disabled');
            }
          });

          if (+data.mutualType === 3) {
            $planList.removeClass('hide');
          }

          util.layerOpen({
            title: false,
            content: $layerPlan,
            area: ['1000px', ''],
            btn: ['修改', '取消'],
            yes: function (index) {
              savePlan();
            }
          });
        });
      });

    }));

    var $validate = $formPlan.validate({
      rules: {
        planCode: { required: true, maxlength: 20 },
        invitCode: { required: true, maxlength: 20 },
        codeType: { required: true },
        startNum: { required: true, maxlength: 20 },
        planName: { required: true, maxlength: 20 },
        cooperationChannel: { required: true, maxlength: 20 },
        receiveLimt: { required: true, number: true },
        validDate: { required: true },
        mutualType: { required: true }
      },
      messages: {
        planCode: { required: '请输入营销方案编号' },
        invitCode: { required: '请输入邀请码' },
        codeType: { required: '请选择编号生成方式' },
        startNum: { required: '请输入起始数字' },
        planName: { required: '请输入方案名称' },
        cooperationChannel: { required: '请输入合作渠道' },
        receiveLimt: { required: '请输入领取上限', number: '请输入有效数字' },
        validDate: { required: '请选择有效期' },
        mutualType: { required: '请选择互斥方案' }
      },
      errorPlacement: function (error, element) { // 错误信息位置设置方法
        error.appendTo(element.parents('.form-container')); // 这里的element是录入数据的对象
      }
    });

    // 优惠券方案保存
    function savePlan() {

      var data = util.formData($formPlan);

      util.toTimeStamp(data, [
        'validityStartTime',
        'validityEndTime'
      ]);

      // 互斥方案数据
      data.appointMutexList = (function () {
        var ret = [];
        if (data.mutualType === '3') {
          $planList.find('input').each(function () {
            var $this = $(this);
            var temp = {};
            if ($this.prop('checked')) {
              temp = {
                mutexId: $this.val(),
                mutexName: $this.next().text()
              };
              if (data.kid) {
                temp.planId = data.kid;
              }
              ret.push(temp);
            }
          });
        }
        return ret;
      })();
      // 派券方案数据
      data.couponDetailList = (function () {
        var ret = [];
        $couponList.find('input[type="checkbox"]').each(function () {
          var $this = $(this);
          var temp = {};
          if ($this.prop('checked')) {
            temp = {
              couponId: $this.val(),
              couponName: $this.next().text(),
              type: 1,
              couponQty: $this.parent().next().val()
            };
            if (data.kid) {
              temp.planId = data.kid;
            }
            ret.push(temp);
          }
        });
        return ret;
      })();

      data.updateId = oUser.userId;
      data.updateTime = $.now();
      data.createId = oUser.userId;
      data.createTime = $.now();
      data.status = 0;

      if (data.mutualType === '3' && data.appointMutexList.length === 0) {
        return util.tip.warn('请选择至少一个互斥方案');
      }

      // console.log(data);

      if ($validate.form()) {
        if ($formPlan.find('.error').filter(':visible').length > 0) {
          return util.tip.warn('检测到有输入错误，请更正后重新提交');
        }

        layer.confirm('确认提交当前数据？', function () {
          util.post(ajaxURL.COUPON + (data.kid ? '/coupon/v1/plan/update' : '/coupon/v1/plan/save'), data, function (res) {
            layer.closeAll();
            util.tip.success('操作成功');
            $tablePlan.trigger('reloadGrid');
          });
        });
      }
    }


  });

})(window, jQuery);
